package org.finesys.ai.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.security.SecurityRequirement;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.finesys.ai.constants.AigcControllerRestApiConfig;
import org.finesys.ai.entity.AigcProviderModel;
import org.finesys.ai.service.AigcProviderModelService;
import org.finesys.ai.vo.AigcProviderModelExcelVO;
import org.finesys.common.core.constants.RestApiConfig;
import org.finesys.common.core.constants.ValidationGroup;
import org.finesys.common.core.module.R;
import org.finesys.common.core.util.ValidationUtil;
import org.finesys.common.excel.annotaion.ResponseExcel;
import org.finesys.common.log.core.annotation.LogAnnotation;
import org.finesys.common.log.core.enums.OperateType;
import org.finesys.system.api.entity.SysDictItem;
import org.finesys.system.api.service.DictService;
import org.springframework.http.HttpHeaders;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Tag(name = "Aigc供应商模型管理")
@RestController
@RequestMapping(value = AigcControllerRestApiConfig.AIGC_PROVIDER_MODLE)
@RequiredArgsConstructor
@SecurityRequirement(name = HttpHeaders.AUTHORIZATION)
public class AigcProviderModelController {

    private final AigcProviderModelService aigcProviderModelService;

    private final DictService dictService;

    /**
     * 添加
     */
    @Operation(summary = "添加")
    @LogAnnotation(title = "Aigc供应商模型管理", operateType = OperateType.INSERT)
    @PostMapping(value = RestApiConfig.ADD)
    @PreAuthorize("@pms.hasPermission('aigc_provider_model_add')")
    public R<Void> add(@RequestBody AigcProviderModel aigcProviderModel) {
        ValidationUtil.validateParam(aigcProviderModel, ValidationGroup.add.class);
        return R.judge(aigcProviderModelService.save(aigcProviderModel));
    }

    /**
     * 修改
     */
    @Operation(summary = "修改")
    @LogAnnotation(title = "Aigc供应商模型管理", operateType = OperateType.UPDATE)
    @PreAuthorize("@pms.hasPermission('aigc_provider_model_edit')")
    @PutMapping(value = RestApiConfig.UPDATE)
    public R<Void> update(@RequestBody AigcProviderModel aigcProviderModel) {
        ValidationUtil.validateParam(aigcProviderModel, ValidationGroup.update.class);
        return R.judge(aigcProviderModelService.updateById(aigcProviderModel));
    }

    /**
     * 删除
     */
    @Operation(summary = "删除")
    @DeleteMapping(value = RestApiConfig.DELETE)
    @LogAnnotation(title = "Aigc供应商模型管理", operateType = OperateType.DELETE)
    @PreAuthorize("@pms.hasPermission('aigc_provider_model_delete')")
    public R<Boolean> delete(@RequestBody String[] ids) {
        return R.judge(aigcProviderModelService.removeBatchByIds(Arrays.asList(ids)));
    }

    /**
     * 获取单条
     */
    @Operation(summary = "获取单条")
    @GetMapping(value = RestApiConfig.GET + "/{id}")
    public R<AigcProviderModel> findById(@PathVariable String id) {
        return R.success(aigcProviderModelService.getById(id));
    }

    /**
     * 获取全部
     */
    @Operation(summary = "获取全部")
    @GetMapping(value = RestApiConfig.ALL)
    public R<List<AigcProviderModel>> findAll() {
        List<AigcProviderModel> list = aigcProviderModelService.findAll();
        updateProviderName(list);
        return R.success(list);
    }

    /**
     * 获取数据
     */
    @Operation(summary = "获取数据")
    @PostMapping(value = RestApiConfig.LIST)
    public R<List<AigcProviderModel>> findList(@RequestBody AigcProviderModel aigcProviderModel) {
        List<AigcProviderModel> list = aigcProviderModelService.findList(aigcProviderModel);
        //更新供应商名称字段
        updateProviderName(list);
        return R.success(list);
    }

    /**
     * 获取数据
     */
    @Operation(summary = "获取数据")
    @GetMapping(value = "findProviderList")
    public R<List<AigcProviderModel>> findProviderList(String modelType) {
        List<AigcProviderModel> list = aigcProviderModelService.findProviderList(modelType);
        updateProviderName(list);
        return R.success(list);
    }

    private void updateProviderName(List<AigcProviderModel> list) {
        R<List<SysDictItem>> dictList = dictService.getDictByType("LLM_PROVIDER");
        if (dictList.isSuccess()) {
            Map<String, String> dictMap = dictList.getData().stream().collect(Collectors.toMap(SysDictItem::getItemValue, SysDictItem::getLabel, (k1, k2) -> k1));
            list.forEach(item -> {
                item.setProviderName(dictMap.getOrDefault(item.getProvider(), "未知供应商"));
            });
        }
    }

    /**
     * 分页查询
     *
     * @param page 分页对象
     * @return
     */
    @Operation(summary = "分页查询", description = "分页查询")
    @GetMapping(RestApiConfig.PAGE)
    public R<?> page(Page<AigcProviderModel> page, AigcProviderModel aigcProviderModel) {
        //增加排序功能
        if (page.orders().isEmpty()) {
            page.addOrder(aigcProviderModelService.getOrders());
        }
        Page<AigcProviderModel> pageResult = aigcProviderModelService.findPage(page, aigcProviderModel);
        if (pageResult != null && pageResult.getRecords() != null && !pageResult.getRecords().isEmpty()) {
            updateProviderName(pageResult.getRecords());
        }
        return R.success(pageResult);
    }

    /**
     * 导出excel 表格
     *
     * @return
     */
    @ResponseExcel
    @GetMapping(RestApiConfig.EXPORT_EXCEL)
    @PreAuthorize("@pms.hasPermission('aigc_provider_model_export')")
    public List<AigcProviderModelExcelVO> exportExcel() {
        return aigcProviderModelService.listExcel();
    }
}
